package com.woniu.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.woniu.pojo.Course;
import com.woniu.pojo.Order;
import com.woniu.service.ICourseService;
import com.woniu.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author xiaoruan
 * @since 2023-03-22
 */

@Controller
@RequestMapping("/order")
public class OrderController {



    @Autowired
    IOrderService orderService;


    @Autowired
    private ICourseService courseService;

    //跳转到order页面
    @GetMapping("/toOrder/{courseId}")
    public String toOrder(@PathVariable String courseId, Model model){
        // 1. 根据课程ID查询课程数据
        Course course = courseService.getById(courseId);
        // 2. 将课程数据绑定到前端页面
        model.addAttribute("course", course);
        // 3. 返回支付页面的视图名称
        return "order";
    }

    //立即支付后访问下面的方法
    @GetMapping("order/{courseId}")
    public void order(@PathVariable String courseId, HttpSession session, HttpServletResponse httpResponse){
//      String userId= (String) session.getAttribute("user_id"); 这两行代码等写完登录的时候要记得改
        String userId="666";
      Order order = orderService.saveOrder(courseId,userId);

        // 2. 跳转到支付页面
        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",
                "2021000122610709",
                "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCFdEgBoP8TXaChPzm98vQQ2PqVcxRV/azV3SDMyGlucGvucJG5OY7EZGHeveo8xkj+pqTPZGLCAUwF+W7V4ZiBPjEX9wDHZjowqDFRPfcAf46JOTb5g0gRzp0DolA36EXfJuX9naM3Mrw0Z5VBXXyU5QGktxQB//2IeJLERWUEciaABzkjbpgBrnl+5k2aiIU7zKCu22bywVyzZkLF/tRcF4mhQq110z7ZUED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IBiYwEyYq3pmsQPHxhk4rw9+/MERa3DwWREQCWkfH+1sAOB8j2zp5HiXHMUzMPzElB0V2yqv0S9JJ8CgYBhZGFY62QyQY4OKutNJJNXOajVZMCfG5IbGgDk4V6yrP6a9dQ+eDFlVTKSGJKbBSPUlcBt282hO/8YBt0oNXBo48WtNe57k5339NvJn45fxflvfAOLGXXSEFUfHgrVYMdsI5WTkCWI4JWol2ldaeAP65F9oUIb7uf/xYW55zi/dA==",
                "json",
                "UTF-8",
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjxxGuV2svDly0AHU/+1yJEvOMkZ67Ems3GhUMOeJqe4USVaD4reeSRUH8h48MZGuDlBDucpE188KZwPM7cYJIH+xMWY2C6jwQnpcoFj/MYSPPguUR9krr12sokLLYSiM0fLg5E8HmBjC4Mkx1AL3E2sMeAhrbkZdJ9FVXKs7m6bkpmgFvqKPYbw7Ce5P1T5wth7aKfTi+Dpj5IzarImydnUUg2U/kwpyKhk08tuWe/efe4H3gm1IOEX/u8/brnh9eqPJr3Pw0syfkmF80ssu1q+tWXVLJ3Sj//+/KwjE2IfK9ge4tQnZOPV8Oq2ogdqT/Ivkip8C7387SzFM0nC9qQIDAQAB", "RSA2");  //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); //创建API对应的request
        alipayRequest.setReturnUrl("http://mmvcft.natappfree.cc/order/return_url");
        alipayRequest.setNotifyUrl("http://mmvcft.natappfree.cc/order/notify_url"); //在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":"+order.getId()+"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":"+order.getPrice()+"," +
                "    \"subject\":\"Iphone6 16G\"," +
                "    \"body\":\"Iphone6 16G\"," +
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                "    \"extend_params\":{" +
                "    \"sys_service_provider_id\":\"2088511833207846\"" +
                "    }" +
                "  }"); //填充业务参数
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
            System.out.println(form);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + "UTF-8");
        try {
            httpResponse.getWriter().write(form); //直接将完整的表单html输出到页面

            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @GetMapping("/return_url")
    public String return_url(){
        System.out.println("支付宝沙箱支付的同步回调回来了。。。。。。。。。。。。。。。。。。。");
        // 同步回调，跳转页面
        return "login";
    }

    @PostMapping("/notify_url")
    @ResponseBody
    public String notify_url(){
        System.out.println("支付宝沙箱支付的yyi步回调回来了=========================");
        // 同步回调，跳转页面
        return "success";
    }
}
